package com.xiaoerkeji.eshop.plug;

import android.Manifest;
import android.app.Activity;
import android.os.Build;
import android.view.Gravity;

import com.xiaoerkeji.eshop.R;
import com.xiaoerkeji.eshop.listener.MyDialogListener;
import com.xiaoerkeji.eshop.listener.MyInterface;
import com.xiaoerkeji.eshop.ui.dialog.DialogFactory;
import com.xiaoerkeji.eshop.ui.dialog.DialogFileDown;
import com.xiaoerkeji.eshop.xeApp;
import com.xiaoerkeji.eshop.xeConstant;
import com.lt.app.InstallHelper;
import com.lt.app.IntentHelper;
import com.lt.listener.ResultCallBack;

import java.io.File;
import java.io.IOException;

import androidx.core.app.ActivityCompat;

/**
 * Created by tianlan on 2017/12/13.
 */

public class UpdateHelper
{
    private final String TAG = this.getClass().getSimpleName();
    private DialogFileDown mDialogFileDown;
    private DialogFactory mDialogFactory;
    private Activity act;
    private String url;
    private String version;
    private String content;

    public UpdateHelper(Activity activity)
    {
        this.act = activity;
    }

    /**
     * 判断是否是8.0,8.0需要处理未知应用来源权限问题,否则直接安装
     */
    public void update(final String url, final String version, final String content)
    {
        this.url = url;
        this.version = version;
        this.content = content;
        if (Build.VERSION.SDK_INT >= 26)
        {
            boolean b = act.getPackageManager().canRequestPackageInstalls();
            if (b)
            {
                download();
            } else
            {
                //请求安装未知应用来源的权限
                ActivityCompat.requestPermissions(act, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, xeConstant.INSTALL_PACKAGES_REQUEST_CODE);
                xeApp.getInstance().showToast(R.string.tip_install_8);
//                showDialog(ResUtils.getString(R.string.tip_install_p_8));
            }
        } else
        {
            download();
        }

    }


    private void download()
    {

        mDialogFileDown = new DialogFileDown(act);
        mDialogFileDown.show(version, content, new MyInterface.OnDialogCountDownListener()
        {
            @Override
            public void onClickLeftButton()
            {

            }

            @Override
            public void onClickRightButton()
            {
            }

            @Override
            public void onTimeOver()
            {
            }

            @Override
            public void onClose()
            {
            }

            @Override
            public void onDismiss()
            {
            }
        });

        new InstallHelper(act, url, xeApp.getInstance().getLogDir().getAbsolutePath() + "/", "new.apk", new InstallHelper.DownloadCallBack()
        {
            @Override
            public void onStart()
            {
                if (mDialogFileDown != null && mDialogFileDown.isShowing())
                {
                    mDialogFileDown.start();
                }
            }

            @Override
            public void onComplete(String path)
            {
                if (mDialogFileDown != null && mDialogFileDown.isShowing())
                {
                    mDialogFileDown.complete();
                }
                String[] command = {"chmod", "777", path};
                ProcessBuilder builder = new ProcessBuilder(command);
                try
                {
                    builder.start();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
                IntentHelper.getInstance().installAPK(act, new File(path), new ResultCallBack()
                {
                    @Override
                    public void onSuccess()
                    {
                        closeAllDialog();
                        xeApp.getInstance().showToast(R.string.upgrade_install);
                        System.exit(0);
                    }

                    @Override
                    public void onFail(Exception e)
                    {
                        closeAllDialog();
//                        UmUtils.reportError(act, TAG, "安装失败：" + e.getMessage());
                        showDialog("升级出现错误，安装失败");
                    }
                });
            }

            @Override
            public void onLoading(long total, long current)
            {
                if (mDialogFileDown != null && mDialogFileDown.isShowing())
                {
                    mDialogFileDown.updateView(current, total);
                }
            }

            @Override
            public void onFail(String err)
            {
                closeAllDialog();
                showDialog(err);
            }

        }).downloadAPK();
    }

    private void showDialog(String title, String content, String left,
                            String right, int gravity, MyDialogListener listener)
    {
        if (act != null && !act.isFinishing())
        {
            if (mDialogFactory == null)
            {
                mDialogFactory = new DialogFactory(act);
            }
            if (mDialogFactory.isShow())
            {
                mDialogFactory.close();
            }
            mDialogFactory.show(title, content, left, right, gravity, listener);
        }
    }

    private void showDialog(String content)
    {
        showDialog(null, content, null, null, Gravity.CENTER_HORIZONTAL, null);
    }

    private void closeAllDialog()
    {
        if (mDialogFactory != null && mDialogFactory.isShow())
        {
            mDialogFactory.close();
        }
        if (mDialogFileDown != null && mDialogFileDown.isShowing())
        {
            mDialogFileDown.closeSlef();
        }
    }


}
